<template>
	<view class="content">
		<view class="custom">
			<view style="width: 44px;height: 24px;font-size: 18px;color: rgba(16,16,16,1);font-weight: bold;">亿想</view>
		</view>
		<scroll-view 
            class="content-box" 
			:scroll-with-animation="true"
            :scroll-y="true" 
			id="myScroll"
			:scroll-top="scrollTop" 
            style="height: 100%;" 
       >
		<view style="margin-top: 100px;">
			<view class="body" v-if="!loading">
			<view v-for="(item, index) in arr" :key="index" :id="'message' + item.message_id">
				<view v-if="item.role === 'assistant'">
					<view style="display: flex; align-items: center;">
						<image style="width: 70rpx;height: 70rpx;" :src="panda" mode="aspectFill"></image>
						<view style="margin-left: 5px;font-size: 14px;">亿想</view>
					</view>
					<view style="margin-top: 25rpx;" class="body_box">
						<view class="body_jt">
						</view>
						<!-- 若存在思考过程内容，显示折叠组件，放到正式内容上方 -->
						<view class="body_rcon pdg" style="padding-top:-12px;margin-left: 35rpx;">
							<!-- 显示正常回复内容 -->
							 <view style="display: flex;flex-direction: row-reverse;color: rgba(145,149,157,0.6);font-size: 8px;margin-right: 10px;margin-top: 10px;">
								<view>以下回答内容为Al生成</view>
							 </view>
							 <view v-if="item.show && index !==0" @click="fold(item,index)" style="display: flex;align-items: center;margin-left: 20rpx;color: #91959D;font-size: 12px;margin-top: 12rpx;">
								<image style="width: 15px;height: 15px;" src="/static/jiqi.png" mode="aspectFill"></image>
								<view>已完成深度思考(DeepSeek-R1模型)</view>
								<image style="width: 15px;height: 15px;" src="/static/down.png" mode="aspectFill"></image>
							 </view>
							 <view v-if="!item.show && index !== 0" @click="fold(item,index)" style="display: flex;align-items: center;margin-left: 20rpx;color: #91959D;font-size: 12px;margin-top: 12rpx;">
								<image style="width: 15px;height: 15px;" src="/static/jiqi.png" mode="aspectFill"></image>
								<view>已完成深度思考(DeepSeek-R1模型)</view>
								<image style="width: 15px;height: 15px;" src="/static/up.png" mode="aspectFill"></image>
							 </view>
							 <view v-if="item.show" style="color: rgba(145,149,157,1);font-size: 12px;">
								<zero-markdown-view :markdown="item.typeingThinkContent" :istype="false"></zero-markdown-view>
							 </view>
							<view style="color: rgba(16,16,16,1);font-size: 16px;">
								<zero-markdown-view :markdown="item.typeingContentWithoutThink" :istype="true"></zero-markdown-view>
							</view>
							<view style="position: absolute;right: 0;bottom: -25rpx;">
								<image v-if="index !== 0" style="width: 19px;height: 19px;" @click="copy(item)" src="/static/copy.png" mode="aspectFill"></image>
						    </view>
						</view>
					</view>
				</view>
				<view style="margin-top: 35rpx;" class="body_r" v-if="item.role === 'user'">
					<view class="body_box">
						<view class="body_rcon pdg" style="background-color:#4C76D9;color: #fff;">
							<zero-markdown-view :markdown="item.content" ></zero-markdown-view>
						</view>
					</view>
				</view>
			</view>
			<view v-if="!loading && arr.length > 1" style="width: 100%;margin-top: 20rpx;">
				<view style="display: flex;justify-content: center;align-items: center;">
					<view @click="goIndex">
						<view style="margin-top: 4px;">
							<image style="width:116px;height: 39px;" src="/static/duihua.png"></image>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="body" v-if="loading" id="loading">
			<view style="" class="body_r" >
					    <view class="body_box">
						    <view class="body_rcon pdg" style="background-color:#4C76D9;color: #fff;">
							    <zero-markdown-view :markdown="copyPrompt" ></zero-markdown-view>
						    </view>
					    </view>
				    </view>
				<view style="display: flex; align-items: center;">
					<image style="width: 70rpx;height: 70rpx;" :src="panda" mode="aspectFill"></image>
					<view style="margin-left: 5px;font-size: 14px;">亿想</view>
				</view>
			<view class="body_box" style="padding-top: 40rpx;">
				<view class="body_lcon pdg" style="display: flex;overflow-x: hidden;max-width: 600rpx;">
					<view v-if="!typeingThinkContent" style="padding: 30rpx;">思考中...</view>
					<view v-else class="body_rcon pdg" style="margin-left: 35rpx;">
						<!-- 若存在实时思考过程内容，显示折叠组件，放到正式内容上方 -->
						<view style="display: flex;flex-direction: row-reverse;color: rgba(145,149,157,0.6);font-size: 8px;margin-right: 10px;padding-top: 5px;">
								<view>以下回答内容为Al生成</view>
							 </view>
							 <view v-if="showText" style="display: flex;align-items: center;margin-left: 20rpx;color: #91959D;font-size: 12px;margin-top: 15rpx;" @click="foldText" >
								<image style="width: 15px;height: 15px;" src="/static/jiqi.png" mode="aspectFill"></image>
								<view>深度思考中(DeepSeek-R1模型)</view>
								<image style="width: 15px;height: 15px;" src="/static/down.png" mode="aspectFill"></image>
							 </view>
							 <view v-if="!showText" style="display: flex;align-items: center;margin-left: 20rpx;color: #91959D;font-size: 12px;margin-top: 15rpx;" @click="foldText">
								<image style="width: 15px;height: 15px;" src="/static/jiqi.png" mode="aspectFill"></image>
								<view>深度思考中(DeepSeek-R1模型)</view>
								<image style="width: 15px;height: 15px;" src="/static/up.png" mode="aspectFill"></image>
							 </view>
						<!-- 显示实时正常回复内容 -->
						<view v-if="typeingThinkContent && showText" style="color: rgba(145,149,157,1);font-size: 12px;line-height: 1.5;">
							<zero-markdown-view :markdown="typeingThinkContent" :istype="false"></zero-markdown-view>
						 </view>
						<view v-if="typeingContentWithoutThink" :style="{color: !typeingThinkContent? 'rgba(145,149,157,1)': 'rgba(16,16,16,1)', fontSize:typeingThinkContent? '16px': '12px' }">
							<zero-markdown-view :markdown="typeingContentWithoutThink" :istype="true"></zero-markdown-view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="flooer">
			<view class="flooer_l">
				<u-textarea v-model="prompt" :placeholder="placeholderName" border="none" autoHeight
					style="background-color: #F6F7FB;" :maxlength="256" holdKeyboard :showConfirmBar="false"
					:cursorSpacing="28"></u-textarea>
			</view>
			<view v-if="phonenumber" class="flooer_r pdg">
				<view class="flooer_rpic a" style="background-color: cornflowerblue;"  @click="sendout">
					<image style="" src="../../static/fasong.png" mode="aspectFill"></image>
				</view>
				<!-- <view v-if="loading" class="flooer_rpic a" style="background-color: cornflowerblue;"  @click="zhongzhi">
					<image style="" src="../../static/zhongzhi.png" mode="aspectFill"></image>
				</view> -->
			</view>
			<view v-else class="container">
                <!-- 相对定位容器 -->
                <view class="relative-container">
                    <!-- 按钮（实际在上方，接收点击） -->
                    <button class="transparent-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"></button>
                    <!-- 图片（视觉上在上方，但不拦截点击） -->
                    <image
                        src="../../static/fasong.png"
                        mode="widthFix"
                        class="overlay-image"
                        >
					</image>
                 </view>
            </view>
		</view>
		<view style="height: 198rpx;"></view>
		</view>
	</scroll-view>
	</view>
</template>

<script>
	import setting from "@/common/config";
	import { mapState } from "vuex";

	export default {
		data() {
			return {
				prompt: '',
				copyPrompt: '',
				arr: [],
				timer: null,
				loading: false,
				chat_id: '',
				msgId: '',
				typeingText: "",
				fulfillTypeingText: '',
				typeingId: "",
				now_model: {},
				socketTask: null,
				typeingContentWithoutThink: '',
				typeingThinkContent: '',
				heartbeatTimer: null,
				HEARTBEAT_INTERVAL: 30000,
				showText: true,
				styleObject: {
					color: '',
					fontSize: ''
				},
				showContact: false,
				showDevNav: false,
				rede_code: '',
				loginCode: "",
				phonenumber: "",
				userId: "",
				wxAvatar: "",
				openId: "",
				showPay: false,
				code: '',
				firstConversation: '',
				panda: '',
				placeholderName: '',
				scrollTop: 0,
				windowHeight: 0,
				reconnectTimer: null,
				token: '',
				isConnected: true, // 是否连接网络
                networkType: '', // 网络类型（wifi/4g/5g/none等）
				isZhongzhi: false

			};
		},
		computed: {
			...mapState(['config', 'num', 'userInfo'])
		},
		watch: {
			typeingContentWithoutThink(val) {
				if (val) {
					this.showText = false
				}
			},
			isZhongzhi(val) {
				console.log('监听是否终止', val)
				if (val === true) {
					this.arr.push({
						role: 'assistant',
						content: this.typeingContentWithoutThink,
						typeingContentWithoutThink: this.typeingContentWithoutThink,
						typeingThinkContent: this.typeingThinkContent,
						show: false
					});
					this.typeingContentWithoutThink = '';
					this.typeingThinkContent = '';
					this.showText = true
					this.scrollToBottom()
				}
			}
		},
		methods: {
			processThinkingContent(content) {
			},
			onSocketMessage(res) {
				try {
					if (!res.data) {
						return;
					}
					let data;
						try {
							const parsedData = JSON.parse(res.data);
							if (parsedData.data) {
								data = JSON.parse(parsedData.data);
							} else {
								data = parsedData;
							}
						} catch (parseError) {
							console.error('解析 JSON 出错:', parseError, '原始数据:', res.data);
							return;
					    }	
					if (data.choices[0].finish_reason !== 'stop' && this.loading === true) {
						if (data.choices[0].delta.reasoning_content && data.choices[0].delta.reasoning_content !== null) {
							this.typeingThinkContent += data.choices[0].delta.reasoning_content
						}
						if (data.choices[0].delta.content && data.choices[0].delta.content !== null) {
							this.typeingContentWithoutThink += data.choices[0].delta.content
						}
						console.log('什么东西啊', this.typeingContentWithoutThink, this.typeingThinkContent)
						
					} else {
						this.loading = false
						this.arr.push({
							role: 'assistant',
							content: this.typeingContentWithoutThink,
							typeingContentWithoutThink: this.typeingContentWithoutThink,
							typeingThinkContent: this.typeingThinkContent,
							 show: false
						});
						// 重置数据
						this.typeingContentWithoutThink = '';
						this.typeingThinkContent = '';
						this.showText = true
						this.$nextTick(() => {
							this.scrollToBottom()
						})
					}
				} catch (error) {
					console.error('处理消息时出错:', error);
				}
			},
			sendout() {
				console.log('发送')
				this.isZhongzhi = false
				if (this.socketTask && this.prompt !== '') {
					const arrData = {
						role: 'user',
						content: this.prompt
					};
					const chatRequest = {
						messages: [{
							content: this.prompt,
							role: "user"
						}],
						model: "deepseek-r1",
						prompt: "",
						sysPrompt: "",
						stream: true,
						kid: "",
						userId: null,
						sessionId: null,
						appId: "",
						role: "user"
					};
					this.socketTask.send({
						data: JSON.stringify(chatRequest),
						success: (res) => {
							this.loading = true;
							this.copyPrompt = this.prompt
							this.prompt = '';
							console.log('发送成功111', this.arr);
							this.arr.push(arrData);
							uni.hideKeyboard();
						},
						fail: (err) => {
							console.log('发送失败', err);
						}
					});
				}
			},
			copy(item) {
				uni.setClipboardData({
					data: item.typeingContentWithoutThink,
					success: () => {
						uni.showModal({
							title: '提示',
							content: '内容已复制'
						});
					}
				});
			},
			// 启动心跳机制
			startHeartbeat() {
				this.stopHeartbeat();
				this.heartbeatTimer = setInterval(() => {
					// 使用数值 1 来判断 WebSocket 连接是否处于 OPEN 状态
					if (this.socketTask && this.socketTask.readyState === 1) {
						this.socketTask.send({
							data: JSON.stringify({ type: 'heartbeat' }),
							success: () => {
								console.log('心跳消息发送成功');
							},
							fail: (err) => {
								console.error('心跳消息发送失败', err);
							}
						});
					}
				}, this.HEARTBEAT_INTERVAL);
			},
			// 停止心跳机制
			stopHeartbeat() {
				clearInterval(this.heartbeatTimer);
			},
			// 折叠
			fold(item,index) {
				console.log('折叠', item, index)
				this.arr[index].show = !this.arr[index].show
			},
			foldText() {
				this.showText = !this.showText
			},
			goIndex() {
				this.arr = []
				this.getadmin()
			},
			zhongzhi() {
				this.loading = false
				this.isZhongzhi = true
			},
			getPhoneNumber(e) {
				console.log('e', e.detail)
                if (e.detail.errMsg !== 'getPhoneNumber:ok') {
                    // 用户拒绝授权
                    uni.showToast({
                        title: '您拒绝了获取手机号授权',
                        icon: 'none'
                    });
                    return;
                }

        const { encryptedData, iv } = e.detail;

        // 先调用 wx.login 获取 code
        wx.login({
          success: (res) => {
            if (res.code) {
              this.loginCode = res.code;
              if (!encryptedData || !iv || !this.loginCode) {
                uni.showToast({
                  title: '获取手机号信息失败',
                  icon: 'none'
                });
                return;
              }

              this.$request('/auth/wxMiniPhoneLogin', 'POST', {
                code: this.loginCode, // 使用 wx.login 获取的 code
                encryptedData,
                iv,
                tenantId: '00001'
              }, {
                'content-type': 'application/json'
              })
                  .then((res) => {
                    if (res.code === 200) {
                      console.log('登录成功');
                      uni.showToast({
                        title: '登录成功',
                        icon: 'success'
                      });
                      // 可以在这里添加登录成功后的逻辑，如跳转到首页等
					  const token = res.data.token
							if (token) {
								uni.setStorageSync('token', token)
									this.$request('/wx/user/getInfo', 'GET', {
											}).then(item => {
												console.log('用户信息', item)
                                                uni.setStorageSync('userInfo', item.data)
												console.log('存下来', uni.getStorageSync('userInfo'));
												const userInfo = uni.getStorageSync('userInfo');
												this.phonenumber = userInfo.phonenumber
			                                    this.userId = userInfo.userId
			                                    this.openId = userInfo.openid
			                                    this.wxAvatar = userInfo.wxAvatar
												uni.reLaunch({
									                url: "/pages/index/index"
								                })
												console.log('重新跳转了', this.phonenumber)
											})
										}
                    } else {
                      console.error('登录失败', res);
                      uni.showToast({
                        title: '登录失败，请重试',
                        icon: 'none'
                      });
                    }
                  })
                  .catch((err) => {
                    console.error('请求出错', err);
                    uni.showToast({
                      title: '网络请求出错',
                      icon: 'none'
                    });
                  });
            } else {
              uni.showToast({
                title: '获取登录凭证失败',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            console.error('wx.login 调用失败', err);
            uni.showToast({
              title: '获取登录凭证失败',
              icon: 'none'
            });
          }
        });
			},
			// 获取后台配置
			getadmin() {
				this.$request('/auth/config/list', 'GET', {
				}).then((res) => {
					console.log('后台配置', res)
					if (res.code === 200) {
						const data = res.data
						data.forEach(item => {
							if (item.configName==='welcomeText') {
								this.firstConversation = item.configValue
								this.arr.push({
				                    role: 'assistant',
				                    typeingContentWithoutThink: this.firstConversation,
			                    })
							} else if (item.configName === 'botImage') {
								this.panda = item.configValue
							} else if (item.configName === 'holderPlace') {
								this.placeholderName = item.configValue
							}
						});
					}
				})
			},
			
			scrollToBottom() {
				this.$nextTick(() => {
					this.scrollTop = 10
					const query = uni.createSelectorQuery().in(this);
					query.select('#myScroll').boundingClientRect((res) => {
						const scrollHeight = res.height; // 容器总滚动高度
						console.log('获取的', scrollHeight, this.windowHeight)
						this.scrollTop = scrollHeight
							uni.pageScrollTo({
								scrollTop: 1000000,
								duration:500
							})
						// if (scrollHeight < this.windowHeight) {
						// 	return
						// } else {
						// }
					}).exec()
				})
			},
			// webScoket重连机制
			reconnect() {
				if (this.reconnectTimer) return
				this.reconnectTimer = setTimeout(() => {
					this.creataSocketTask()
					this.reconnectTimer = null
				}, 3000)
			},
			creataSocketTask() {
			    // 创建 WebSocket 连接
			    this.socketTask = uni.connectSocket({
				    url: encodeURI(setting.ws + "?Authorization=Bearer " + this.token),
				        success: () => {
					        console.log('WebSocket  连接成功');
					        this.startHeartbeat();
				        },
				        fail: (err) => {
					    console.error('WebSocket  连接失败', err);
				   }
			    });
				this.socketTask.onOpen(() => {
				    console.log('WebSocket  连接已打开');
			    });
				this.socketTask.onMessage((res) => {
					if (!this.loading) {
						return
					}
				    this.onSocketMessage(res);
			    });
				this.socketTask.onClose((res) => {
				    console.log('WebSocket 连接关闭，原因:', res);
				    this.stopHeartbeat();
					this.reconnect()
			    });
				this.socketTask.onError((err) => {
				    console.error('WebSocket  连接错误', err);
			    });
			},
            // 获取当前网络状态（初始化用）
            getCurrentNetworkStatus() {
                uni.getNetworkType({
                    success: (res) => {
                    this.isConnected = res.networkType !== 'none';
                   this.networkType = res.networkType;
               }
           });
    },
    // 开始监听网络状态变化
    startNetworkListener() {
      // 保存监听函数的引用，用于后续移除
      this.networkListener = (res) => {
        // res包含两个关键参数：
        // - isConnected：布尔值，是否连接网络
        // - networkType：字符串，网络类型（wifi/4g/5g/none等）
        this.isConnected = res.isConnected;
        this.networkType = res.networkType;
        
        // 可根据网络状态变化添加自定义逻辑
        if (!res.isConnected) {
          uni.showToast({
            title: '网络已断开',
            icon: 'none',
            duration: 2000
          });
        } else {
          uni.showToast({
            title: `已切换至${res.networkType}`,
            icon: 'none',
            duration: 2000
          });
		  this.creataSocketTask()
        }
      };
      
      // 注册监听
      uni.onNetworkStatusChange(this.networkListener);
    },
    // 停止监听网络状态变化
    stopNetworkListener() {
      if (this.networkListener) {
        uni.offNetworkStatusChange(this.networkListener);
      }
    },

	//取消
	quxiao() {
		console.log('取消')
		
	}

		},
		onLoad() {
			 // 1. 初始化时先获取当前网络状态
			 this.getCurrentNetworkStatus();
            // 2. 监听网络状态变化
            this.startNetworkListener();
			uni.getSystemInfo({
				success:(res) => {
					console.log('系统信息', res)
					this.windowHeight = res.windowHeight
				}
			})
			this.getadmin()
			const userInfo = uni.getStorageSync('userInfo');
			this.token = uni.getStorageSync('token');
			this.phonenumber = userInfo.phonenumber
			this.userId = userInfo.userId
			this.openId = userInfo.openid
			this.wxAvatar = userInfo.wxAvatar
			this.msgId = userInfo.userId;
			uni.setNavigationBarTitle({ title: "亿想" });
			// 创建 WebSocket 连接
			// this.socketTask = uni.connectSocket({
			// 	url: encodeURI(setting.ws + "?Authorization=Bearer " + token),
			// 	success: () => {
			// 		console.log('WebSocket  连接成功');
			// 		this.startHeartbeat();
			// 	},
			// 	fail: (err) => {
			// 		console.error('WebSocket  连接失败', err);
			// 	}
			// });
			this.creataSocketTask()
			// this.socketTask.onOpen(() => {
			// 	console.log('WebSocket  连接已打开');
			// });

			// this.socketTask.onMessage((res) => {
			// 	this.onSocketMessage(res);
			// });

			// this.socketTask.onClose((res) => {
			// 	console.log('WebSocket 连接关闭，原因:', res);
			// 	this.stopHeartbeat();
			// });

			// this.socketTask.onError((err) => {
			// 	console.error('WebSocket  连接错误', err);
			// });
		},
		onUnload() {
			this.stopHeartbeat();
			uni.closeSocket();
		}
	};
</script>

<style >
	@import '../../components/css/index.css';
	page {
		background-color: rgba(237,240,249,1)
	}
	.custom {
		padding-top: 50px;
		height: 28px;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: rgba(237,240,249,1)
	}
	.container {
		padding-right: 20px;
}

.relative-container {
  position: relative;
  width: 40px;
  height: 40px;
}

.transparent-btn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 40px;
  height: 40px;
  background-color: rgba(0, 0, 0, 0.3);
  color: white;
  /* border-radius: 40rpx; */
  border: none;
  z-index: 20;
}

.overlay-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 10111;
  background-color: cornflowerblue;

  pointer-events: none;
}
</style>
